<!--
  -    Copyright (c) 2018-2025, infomng All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: infomng
  -->
<template>
  <div class="ks-con">
    <div class="search">
      <div class="search-form">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="时间" style="margin-right: 10px">
            <el-date-picker v-model="searchForm.time" type="monthrange" range-separator="至" start-placeholder="开始月份"
              end-placeholder="结束月份" format="yyyy/MM" value-format="yyyy/MM"></el-date-picker>
          </el-form-item>
          <!-- <el-form-item label="车间" style="margin-right: 10px">
            <el-select v-model="searchForm.shop" placeholder="请选择">
              <el-option
                v-for="item in workshopList"
                :key="item.value"
                :label="item.workshopName"
                :value="item.id"
                clearable
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="产线" style="margin-right: 10px">
            <el-select v-model="searchForm.line" placeholder="请选择">
              <el-option
                v-for="item in productionLineList"
                :key="item.value"
                :label="item.realityLineName"
                :value="item.id"
                clearable
              >
              </el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" @click="onSubmit">搜索</el-button>
            <el-button @click="onReset">清空</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- 内容 -->
    <div class="content_main">
      <el-button style="margin-left: 10px;" type="primary" icon="el-icon-plus" size="small" @click="handleAdd()">新增
      </el-button>
      <basic-container>
        <avue-crud ref="crud" :page.sync="page" :data="tableData" :permission="permissionList"
          :table-loading="tableLoading" :option="tableOption" @search-change="searchChange"
          @refresh-change="refreshChange" @size-change="sizeChange" @current-change="currentChange"
          @row-update="handleUpdate" @row-save="handleSave" @row-del="handleDel">
          <!-- <template slot="menuLeft">
          <el-button
            v-if="
              permissions.generator_customercomplaintrecordledgercopy_export
            "
            class="filter-item"
            plain
            type="primary"
            size="small"
            icon="el-icon-download"
            @click="exportExcel"
            >导出
          </el-button>
        </template> -->
          <!-- 编辑 -->

          <template slot="delFlag" slot-scope="scope">
            <div>{{ scope.row.delFlag == 0 ? "正常" : "已删除" }}</div>
          </template>
          <template slot="problemDescription" slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="scope.row.problemDescription" placement="top-start">
              <div>{{ scope.row.problemDescription }}</div>
            </el-tooltip>
          </template>
          <template slot="reportAttachment" slot-scope="scope">
            <div class="photo-actions" v-if="scope.row.reportAttachment">
              <div style="cursor: pointer; color: #409eff" @click="downFile(scope.row.reportAttachment)">
                下载附件
              </div>
              <div style="cursor: pointer; color: #409eff" @click="viewFile(scope.row.reportAttachment)">
                预览
              </div>
            </div>
          </template>
          <template slot="defectivePhoto" slot-scope="scope">
            <div class="photo-actions" v-if="scope.row.defectivePhoto">
              <div style="cursor: pointer; color: #409eff" @click="downBadPhotoFile(scope.row.defectivePhoto)">
                下载不良图片
              </div>
              <div style="cursor: pointer; color: #409eff" @click="viewBadPhotoFile(scope.row.defectivePhoto)">
                预览
              </div>
            </div>
          </template>
          <template slot="hyperlinkAttachment" slot-scope="scope">
            <div v-if="scope.row.hyperlinkAttachment" class="photo-actions">
              <div style="cursor: pointer; color: #409eff" @click="downFile(scope.row.hyperlinkAttachment)">
                下载超链接
              </div>
              <div style="cursor: pointer; color: #409eff" @click="viewFile(scope.row.hyperlinkAttachment)">
                预览
              </div>
            </div>
          </template>

          <template slot="menu" slot-scope="scope">
            <el-button type="text" size="small" icon="el-icon-edit" @click="handleUpdate(scope.row, scope.index)">编辑
            </el-button>
            <el-button type="text" size="small" icon="el-icon-delete" @click="handleDel(scope.row, scope.index)">
              删除
            </el-button>
          </template>
        </avue-crud>

        <!-- 编辑保存 -->
        <el-dialog :title="ksId ? '编辑' : '新增'" :visible.sync="dialogVisible" width="60%">
          <div>
            <edit :dialogVisible="dialogVisible" :ksId="ksId" @success="success" @close="dialogVisible = false" />
          </div>
          <!-- <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="dialogVisible = false"
              >确 定</el-button
            >
          </span> -->
        </el-dialog>
      </basic-container>


    </div>

  </div>
</template>

<script>
import {
  fetchList,
  addObj,
  putObj,
  delObj,
} from "@/api/customercomplaintrecordledgercopy";
import { tableOption } from "@/const/crud/workorder/customercomplaintrecordledgercopy";
import { mapGetters } from "vuex";
import AvueUeditor from "avue-plugin-ueditor";
import edit from "./edit.vue";
import { workshop, lineList } from "@/api/common";
import { download, fetchList as fetchFileList } from "@/api/admin/sys-file";
import { Base64 } from 'js-base64';

export default {
  name: "customercomplaintrecordledgercopy",
  data() {
    return {
      tableData: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20, // 每页显示多少条
      },
      tableLoading: false,
      tableOption: tableOption,
      dialogVisible: false,
      ksId: "",
      searchForm: {
        time: [],
        shop: "",
        line: "",
      },
      workshopList: [],
      productionLineList: [],
    };
  },
  comments: {
    AvueUeditor,
  },
  components: {
    edit,
  },
  created() {
    if (this.$route.query.time != null && this.$route.query.time != "") {
      this.searchForm.time = [this.$route.query.time, this.$route.query.time];
    }
    this.onSubmit(this.page);
    //this.getList();
  },
  mounted() {
    this.getWorkshopLists();
    this.getLineLists();
  },
  computed: {
    ...mapGetters(["permissions"]),
    permissionList() {
      return {
        addBtn: this.vaildData(
          this.permissions.generator_customercomplaintrecordledgercopy_add1,
          false
        ),
        delBtn: this.vaildData(
          this.permissions.generator_customercomplaintrecordledgercopy_del1,
          false
        ),
        editBtn: this.vaildData(
          this.permissions.generator_customercomplaintrecordledgercopy_edit1,
          false
        ),
      };
    },
  },
  methods: {
    downFile(path) {
      download(path).then(async (res) => {
        console.log(res.request.responseURL);
        const link = document.createElement("a");
        link.href = res.request.responseURL;
        const result = await fetchFileList({ currentPage: 1, pageSize: 1, fileName: path.substring(path.lastIndexOf('/') + 1) })
        console.log("result", result)
        if (result.status === 200 && result.data.code === 0 && result.data.data.records.length > 0) {
          link.download = result.data.data.records[0].original;
        } else {
          link.download = path.substring(path.lastIndexOf('/') + 1);
        }
        link.click();
      });
    },
    downBadPhotoFile(path) {
      if (path) {
        const pathList = path.split(",");
        console.log("path", pathList)
        pathList.forEach(p => {
          download(p).then(async (res) => {
            console.log(res.request.responseURL);
            const link = document.createElement("a");
            link.href = res.request.responseURL;
            const result = await fetchFileList({ currentPage: 1, pageSize: 1, fileName: p.substring(p.lastIndexOf('/') + 1) })
            console.log("result", result)
            if (result.status === 200 && result.data.code === 0 && result.data.data.records.length > 0) {
              link.download = result.data.data.records[0].original;
            } else {
              link.download = p.substring(p.lastIndexOf('/') + 1);
            }
            link.click();
          });
        })
      }
    },
    viewBadPhotoFile(path) {
      if (path) {
        const pathList = path.split(",");
        const url = pathList.map(p => {
          return window.location.origin + p
        }).join("|")
        window.open(window.location.origin + '/preview/picturesPreview?urls=' + encodeURIComponent(Base64.encode(url)), url.substring(url.lastIndexOf('/') + 1))
      }
    },
    viewFile(path) {
      if (path) {
        const url = window.location.origin + path
        window.open(window.location.origin + '/preview/onlinePreview?url=' + encodeURIComponent(Base64.encode(url)), url.substring(url.lastIndexOf('/') + 1))
      }
    },
    getWorkshopLists() {
      workshop().then((res) => {
        this.workshopList = res.data.data.records;
      });
    },
    getLineLists(wshop) {
      // this.tableData.map
      lineList().then((res) => {
        //   {
        //   workshopId: wshop? wshop : "",
        // }
        this.productionLineList = res.data.data.records;
      });
    },
    onSubmit() {
      let data = {
        // workId: this.searchForm.shop,
        // lineId: this.searchForm.line,
        startTime: this.searchForm.time[0],
        endTime: this.searchForm.time[1],
      };
      console.log(data);

      this.page.currentPage = 1;
      this.getList(this.page, data);
    },
    onReset() {
      this.searchForm = {
        time: "",
        shop: "",
        line: "",
      };
      console.log("重置搜索条件");
    },
    success() {
      this.dialogVisible = false;

      this.getList(this.page);
    },
    handleUpdate: function (row) {
      this.ksId = row.id;
      this.dialogVisible = true;
    },

    handleAdd() {
      this.dialogVisible = true;
      this.ksId = "";
    },

    handleSave: function (row, done, loading) {
      addObj(row)
        .then((data) => {
          this.$message.success("添加成功");
          done();
          this.getList(this.page);
        })
        .catch(() => {
          loading();
        });
    },
    // 列表查询
    getList(page, params) {
      this.tableLoading = true;
      fetchList(
        Object.assign(
          {
            current: page.currentPage,
            size: page.pageSize,
          },
          params
          // this.searchForm
        )
      )
        .then((response) => {
          this.tableData = response.data.data.records;
          this.page.total = response.data.data.total;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    // 删除
    handleDel: function (row, index) {
      this.$confirm("是否确认删除ID为" + row.id, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delObj(row.id);
        })
        .then((data) => {
          this.$message.success("删除成功");
          this.getList(this.page);
        });
    },
    // 每页条数改变事件
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    // 当前页发生改变事件
    currentChange(current) {
      this.page.currentPage = current;
    },
    // 查询事件
    searchChange(form, done) {
      this.searchForm = form;
      this.page.currentPage = 1;
      this.getList(this.page, form);
      done();
    },
    // 刷新事件
    refreshChange() {
      this.getList(this.page);
    },
    //  导出excel
    exportExcel() {
      this.downBlobFile(
        "/generator/customercomplaintrecordledgercopy/export",
        this.searchForm,
        "customercomplaintrecordledgercopy.xlsx"
      );
    },
  },
};
</script>
<style lang="scss" scoped>
.ks-con {
  padding: 0 10px;
}

.search {
  padding: 10px;
  background: #fff;
  margin-bottom: 10px;
}

.content_main {
  background: #fff;
  position: relative;
  box-sizing: border-box;
  padding: 10px 0;
  height: 88%;

  ::v-deep .basic-container {
    background: #fff;
    padding: 0;
  }

  ::v-deep .avue-crud__menu {
    width: 10%;
    position: absolute;
    top: 1%;
    right: 1%;
  }
}

.photo-actions {
  display: flex;
  /* 启用 flex 布局 */
  align-items: center;
  /* 垂直居中对齐 */
  gap: 15px;
  /* 元素间间距 */
}
</style>
